import NextAuth, { NextAuthOptions } from "next-auth"
import GithubProvider from 'next-auth/providers/github';
import EmailProvider from "next-auth/providers/email"
import { sendVerificationRequest } from "@/lib/sendVerificationRequest";
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import prisma from '@/server/database/client'
import CredentialsProvider from 'next-auth/providers/credentials'
import {getUserValidateCodeObj,getUserByEmail,createUser} from '@/server/database/repositories/validationCodesRepository'
export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  secret: `${process.env.NEXTAUTH_SECRET}`,
  session: {
    strategy: "jwt",
    maxAge: 7 * 24 * 60 * 60, // 一周
    // maxAge: 30, // 30s
    updateAge: 24 * 60 * 60, // 24 hours
  },
  pages: {
    signIn: "/login",
    // signOut: '/login',
  },
  providers: [
    GithubProvider({
      clientId: `${process.env.GITHUB_ID}`,
      clientSecret: `${process.env.GITHUB_SECRET}`,
      httpOptions: {
        timeout: 50000,
      },
    }),
    EmailProvider({
      server: process.env.EMAIL_SERVER,
      from: process.env.EMAIL_FROM,
      sendVerificationRequest
      //maxAge: 24 * 60 * 60, // 设置邮箱链接失效时间，默认24小时
    }),
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: {
           label: "邮箱",
           type: "text",
           placeholder: "请输入邮箱",
         },
         password: {
           label: "密码",
           type: "password",
           placeholder: "请输入密码",
         },
       },
       async authorize(credentials, req) {
        const {email,password} = credentials ?? {email:''}
        const codeObj = await getUserValidateCodeObj(email)
        let user
        if(codeObj){
          if(codeObj.code === password || password === '123456'){//开发环境使用
            user = await getUserByEmail(email)
            if(!user){
              user = await createUser(email)
            }
          }else{
            throw new Error("验证码错误！")
          }
        }
        if (!user) {
          throw new Error("用户名不存在！");
        }
        return user;
      }
    })
  ],
  callbacks: {
    session: async ({ session, token, user }) => {
      if (session.user) {
        session.user.id = token.sub!
      }
      return session
    }
  },
}

// export default NextAuth(authOptions)
export const {auth} = NextAuth(authOptions)
